/**
 *
 */
package de.cbf.cam.dsa.rcp.model.persistence.db4o;

import java.util.ArrayList;
import java.util.Collection;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import de.cbf.util.db.db4o.DB4O_DBWrapperUUID;
import de.cbf.util.db.interfaces.exceptions.EntityLoadException;
import de.cbf.util.db.interfaces.exceptions.EntitySaveException;
import de.cbf.util.db.reflective_interface.ReflectiveDBInterface;
import de.cbf.util.uuidheader.entities.UUIDHeader;
import de.cbf.util.uuidheader.interfaces.IUUIDHeader;

/**
 * @author salter
 *
 */
public class RCPEntityPersisterDB4O {

	private static final Log logger = LogFactory.getLog(RCPEntityPersisterDB4O.class);

	protected ReflectiveDBInterface 	reflectiveInterface;
	protected DB4O_DBWrapperUUID 		wrapper;

	public RCPEntityPersisterDB4O() {
		super();
		init();
	}


	protected void init(){
		wrapper = DB4O_DBWrapperUUID.getInstance();
		reflectiveInterface = new ReflectiveDBInterface();//TODO get reflective interface from service
		reflectiveInterface.setObjectiveDBWrapperUUID(wrapper);
	}

	public IUUIDHeader loadEntity(UUIDHeader header) throws EntityLoadException{
		IUUIDHeader result = null;
		if(reflectiveInterface != null){
			result = reflectiveInterface.loadEntity(header);
		}else{
			if(wrapper != null){
				result = wrapper.loadEntity(header);
			}
		}
		return result;
	}

	public IUUIDHeader loadEntity(UUID uuid,Class<?> clazz) throws EntityLoadException{
		IUUIDHeader result = null;
		if(reflectiveInterface != null){
			result = reflectiveInterface.loadEntity(uuid,clazz);
		}else{
			if(wrapper != null){
				result = wrapper.loadEntity(uuid);
			}
		}
		return result;
	}

	public Collection<IUUIDHeader> loadEntities(Class<? extends UUIDHeader> clazz) throws EntityLoadException{
		Collection<IUUIDHeader> result = new ArrayList<IUUIDHeader>();
		result.addAll(wrapper.loadEntitiesByClass(clazz));
		return result;
	}


	public void saveEntity(IUUIDHeader entity) throws EntitySaveException{
		if(reflectiveInterface != null){
			reflectiveInterface.saveObjectIfEntity(entity);
		}else{
			logger.info("no reflective interface present, saving directly");
			if(wrapper != null){
				wrapper.saveEntity(entity);
			}else{
				throw new EntitySaveException("No objective wrapper found for saving");
			}
		}
	}


}
